package com.jzo2o.orders.manager.listener;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.jzo2o.common.constants.MqConstants;
import com.jzo2o.common.model.msg.TradeStatusMsg;
import com.jzo2o.orders.manager.service.IOrdersCreateService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Mr.M
 * @version 1.0
 * @description 监听mq获取支付结果
 * @date 2023/12/14 16:15
 */
@Component
@Slf4j
public class TradeStatusListener {

    @Resource
    private IOrdersCreateService ordersCreateService;

    /**
     * 更新支付结果
     * 支付成功
     *
     * @param msg 消息
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = MqConstants.Queues.ORDERS_TRADE_UPDATE_STATUS),
            exchange = @Exchange(name = MqConstants.Exchanges.TRADE, type = ExchangeTypes.TOPIC),
            key = MqConstants.RoutingKeys.TRADE_UPDATE_STATUS
    ))
    public void listenTradeUpdatePayStatusMsg(String msg) {
        log.info("监听到支付结果消息：{}", msg);

        //解析消息,通过查阅支付服务的源代码，消息内容是List<TradeStatusMsg> 的json格式
        List<TradeStatusMsg> tradeStatusMsgList = JSONObject.parseArray(msg, TradeStatusMsg.class);

        //根据productAppId系统标识判断是不是自己的，家政订单的支付的系统标识是jzo2o.orders
        //还需要只取出statusCode为4的支付成功的结果
        List<TradeStatusMsg> collect = tradeStatusMsgList.stream()
                .filter(item -> "jzo2o.orders".equals(item.getProductAppId()) && item.getStatusCode() == 4)
                .collect(Collectors.toList());
        if (CollectionUtil.isEmpty(collect)) {
            return;
        }
        //更新数据库订单表的支付状态和订单状态
        for (TradeStatusMsg tradeStatusMsg : collect) {
            ordersCreateService.paySuccess(tradeStatusMsg);
        }

    }
}
